#include "../../Header/AppCore/ObjectShader.h"
#include <Graphics\fwShader.h>

ObjectShader::ObjectShader()
	:m_VertexShader(0), m_FragmentShader(0),
	m_Program(0)
{}

GLuint ObjectShader::InitFormFile(char* vt, char* fr)
{
	char* vertexSRC = ShaderSupport::ReadShader(vt);
	if (!vertexSRC)
		return -1;
	char* fragmentSRC = ShaderSupport::ReadShader(fr);
	if (!fragmentSRC)
	{
		SAFE_DEL_ARRAY(vertexSRC);
		return -1;
	}

	InitFormSRC(vertexSRC, fragmentSRC);

	SAFE_DEL_ARRAY(vertexSRC);
	SAFE_DEL_ARRAY(fragmentSRC);
}

GLuint ObjectShader::InitFormSRC(char* vertexSRC, char* fragmentSRC)
{
	m_VertexShader = ShaderSupport::LoadShader(GL_VERTEX_SHADER, vertexSRC);
	//GLuint a = ShaderSupport::LoadShader(GL_VERTEX_SHADER, vertexSRC);
	if (m_VertexShader == 0)
		return -1;

	m_FragmentShader = ShaderSupport::LoadShader(GL_FRAGMENT_SHADER, fragmentSRC);
	if (m_FragmentShader == 0)
	{
		glDeleteShader(m_VertexShader);
		return -1;
	}

	m_Program = ShaderSupport::LoadProgram(m_VertexShader, m_FragmentShader);
	if (m_Program == 0)
	{
		glDeleteShader(m_VertexShader);
		glDeleteShader(m_FragmentShader);
		return -2;
	}

	LoadShaderDataLocation();
}

void ObjectShader::LoadShaderDataLocation()
{
	m_Position = glGetAttribLocation(m_Program, "a_PosL");
	m_Color = glGetAttribLocation(m_Program, "a_Color");
	m_UV = glGetAttribLocation(m_Program, "a_UV");
	m_GrayScaleOption = glGetUniformLocation(m_Program, "u_GrayScale");

	for (int i = 0; i < 11; i++)
		m_Sampler[i] = -1;
	m_Sampler[1] = glGetUniformLocation(m_Program, "u_Sampler_1");
	m_Sampler[2] = glGetUniformLocation(m_Program, "u_Sampler_2");
	m_Sampler[3] = glGetUniformLocation(m_Program, "u_Sampler_3");
	m_Sampler[4] = glGetUniformLocation(m_Program, "u_Sampler_4");
	m_Sampler[5] = glGetUniformLocation(m_Program, "u_Sampler_5");
	m_Sampler[6] = glGetUniformLocation(m_Program, "u_Sampler_6");
	m_Sampler[7] = glGetUniformLocation(m_Program, "u_Sampler_7");
	m_Sampler[8] = glGetUniformLocation(m_Program, "u_Sampler_8");
	m_Sampler[9] = glGetUniformLocation(m_Program, "u_Sampler_9");
	m_Sampler[10] = glGetUniformLocation(m_Program, "u_Sampler_10");

}

void ObjectShader::Destroy()
{
	glDeleteProgram(m_Program);
	glDeleteShader(m_VertexShader);
	glDeleteShader(m_FragmentShader);
}